import { createRouter, createWebHistory, NavigationGuardNext, RouteLocationNormalized } from 'vue-router'
import HomeLayout from '@/layout/HomeLayout.vue'
import Login from '@/views/login'
import Register from '@/views/register'
import routes from './routes.js'
import errorDefault from '@/views/404'
import userStore from '@/store/modules/user.js'
import { showToast } from 'vant'

const router = createRouter({
  history: createWebHistory('/'),
  routes: [
    {
      path: '/',
      component: HomeLayout,
      redirect: '/home',
      children: routes
    },
    {
      path: '/login',
      name: 'Login',
      component: Login,
      meta: {
        title: '登录',
        requireAuth: false
      }
    },
    {
      path: '/register',
      name: 'Register',
      component: Register,
      meta: {
        title: '注册',
        requireAuth: false
      }
    },
    {
      path: '/forgotPass',
      name: 'ForgotPass',
      component: () => import('@/views/forgotPass/index.vue'),
      meta: {
        title: '忘记密码',
        requireAuth: false
      }
    },
    {
      path: '/404',
      name: '404',
      component: errorDefault,
      meta: {
        title: '404',
        requireAuth: false
      }
    },
    // 路由重定向
    { path: '/:pathMatch(.*)*', redirect: '/404' }
  ],
  scrollBehavior() {
    return {
      el: '#app',
      top: 0,
      left: 0,
      behavior: 'smooth'
    }
  }
})

// //路由前置守卫
router.beforeEach((to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext) => {
  const user = userStore()
  const isLoggedIn = user.isLogin()
  const whiteList = ['/login', '/register', '/forgotPass']

  // 已登录且访问登录页或注册页，重定向到首页
  if (isLoggedIn && whiteList.includes(to.path)) {
    const redirectPath = from.path !== '/' ? from.path : '/home'
    next({ path: redirectPath, replace: true })
  }

  // 需要认证但未登录的情况
  if (to.meta.requireAuth && !isLoggedIn) {
    localStorage.setItem('redirectAfterLogin', to.path)
    showToast('请先登录')
    next({ path: '/login', replace: true })
  }

  next()
})

//路由后置守卫
router.afterEach((to) => {
  document.title = `味巷食铺${to.meta.title ? `-${to.meta.title}` : ''}` as string
})

export default router